package routers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"net/http"
	"net/http/httputil"
	"net/url"
	"t11Lib/t11Errors"
	"t11Lib/t11Log"
	"t11Lib/t11Util"
	"亚太-iot-服务器/biz/wxBiz"
	"亚太-iot-服务器/biz/wxBiz/weixinOperator"
	"亚太-iot-服务器/conf"
)

type reverseProxy struct {
}

func (self *reverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	director := func(req *http.Request) {
		*req = *r
		req.URL.Scheme = "http"
		req.URL.Host = conf.AppConfig.PagesHost
	}

	t11Log.Debug("请求静态内容")
	modifyResp := func(rep *http.Response) error {
		if rep.Request.URL.Path == conf.AppConfig.BasePrefix+"/pages" || rep.Request.URL.Path == conf.AppConfig.BasePrefix+"/pages/index.html" {

			signUrl := &url.URL{
				Host:     "app.aptenon.com",
				Path:     rep.Request.URL.Path,
				RawQuery: rep.Request.URL.RawQuery,
				Scheme:   "http",
			}

			appIds := rep.Request.URL.Query()["appId"]
			if len(appIds) == 0 {
				return t11Errors.New("没有appId")
			}

			ticket, err := weixinOperator.MpManager.LoadJsapiTicket(appIds[0], signUrl)
			if err != nil {
				return err
			}
			t11Log.Debuglnf("ticket = %+v, appIds = %v", ticket, appIds)

			ticketBytes, oerr := json.Marshal(ticket)
			if oerr != nil {
				return oerr
			}

			ck := http.Cookie{
				Name:  "jsapiTicket",
				Value: t11Util.Base64UrlEncode(ticketBytes),
				Path:  conf.AppConfig.BasePrefix,
			}
			rep.Header.Add("Set-Cookie", ck.String())

			//读取到code了，在cookie中设置userId
			code := rep.Request.URL.Query().Get("code")
			if code != "" {

				appId := rep.Request.URL.Query().Get("appId")
				if appId == "" {
					return t11Errors.New("非法的appId")
				}

				wxUser, err := weixinOperator.GetWxUserByCode(appId, code)
				if err != nil {
					return err
				}
				t11Log.Debuglnf("wxUser = %+v", wxUser)

				token, err := wxBiz.JwtBiz.CreateWxMpJwtToken(appId, wxUser.Id)
				if err != nil {
					return err
				}

				ck2 := http.Cookie{
					Name:  "userId",
					Path:  conf.AppConfig.BasePrefix,
					Value: token,
					//Expires: time.Now().Add(time.Second * 30),
				}
				rep.Header.Add("Set-Cookie", ck2.String())
			}
		}
		return nil
	}
	proxy := &httputil.ReverseProxy{Director: director, ModifyResponse: func(response *http.Response) error {
		ret := modifyResp(response)
		if ret != nil {
			t11Log.Debuglnf("err = %v", ret)
		}
		return ret
	}}

	proxy.ServeHTTP(w, r)
}
func initPagesReverseProxy() {
	beego.Handler(conf.AppConfig.BasePrefix+"/pages/*", &reverseProxy{})
	beego.Handler(conf.AppConfig.BasePrefix+"/pages2/*", &reverseProxy{})
}
